from collections import OrderedDict

from atomsitecache import AtomsiteCache
from group import ModelledGroup
from exceptions import PDBentityNotFoundException


class Chain :
	'''represents a PDB chain in a model'''
	def __init__(s, dataconnector, model_id, chain_id) :
		s.dc, s.modelid, s.chainid = dataconnector, model_id, chain_id
		s.entry_id = s.dc.getCategory("entry","id","first")
	def getId(s) : return (s.entry_id, s.modelid, s.chainid)
	def getEntryId(s) : return s.entry_id
	def getModelId(s) : return s.modelid
	def getChainId(s) : return s.chainid
	def makeModelledGroups(s) :
		s.groups = OrderedDict()
		modelchains = AtomsiteCache.getCache(s.dc).getHierarchy()
		for resdata in modelchains[s.modelid][s.chainid] :
			s.groups[(resdata[0],resdata[1])] = ModelledGroup(s.dc, s.modelid, s.chainid, resdata[0], resdata[1])
	def getModelledGroups(s) :
		'''a modelled group is identified by model, chain, resnum, insert-code. The complexities of microhet and altcodes etc are hidden within subgroups'''
		if not hasattr(s,'groups') : s.makeModelledGroups()
		return s.groups.values()
	def getModelledGroup(s, resnum, inscode) :
		'''a modelled group is identified by model, chain, resnum, insert-code. The complexities of microhet and altcodes etc are hidden within subgroups'''
		if not hasattr(s,'groups') : s.makeModelledGroups()
		if inscode in ["."," ","?"] :
			for ic in ["."," ","?"] :
				try : return s.groups[(resnum,ic)]
				except KeyError : pass
		try : return s.groups[(resnum,inscode)]
		except KeyError : raise PDBentityNotFoundException("No residue found with resnum,icode as " + str(resnum) + " and " + str(inscode))
